using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;

namespace Admin.NET.Application.Job;

[JobDetail("job_MeterOnlineJob", Description = "电表采集器在线离线控制", GroupName = "default", Concurrent = false)]
[Daily(TriggerId = "trigger_MeterOnlineJob", Description = "电表采集器在线离线控制")]
internal class MeterOnlineJob : IJob
{
	private readonly IServiceProvider _serviceProvider;

	public MeterOnlineJob(IServiceProvider serviceProvider)
	{
		_serviceProvider = serviceProvider;
	}

	async Task IJob.ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
	{
		using IServiceScope serviceScope = _serviceProvider.CreateScope();
		SqlSugarRepository<Collector> rep = serviceScope.ServiceProvider.GetService<SqlSugarRepository<Collector>>();
		try
		{
			SysConfigService configService = serviceScope.ServiceProvider.GetService<SysConfigService>();
			int result = await configService.GetConfigValue<int>("sys_meter");
			if (result <= 0)
			{
				return;
			}
			DateTime now = DateTime.Now.AddMinutes(-result);
			List<Collector> coolect = rep.GetList((Collector u) => u.Status == 1 && u.LastOnlineTime < now && u.IsDelete == false);
			if (coolect != null && coolect.Count > 0)
			{
				await rep.Context.Ado.BeginTranAsync();
				List<long> collectorIds = coolect.Select((Collector u) => u.Id).ToList();
				coolect.ForEach(delegate(Collector u)
				{
					u.Status = 0;
				});
				rep.Context.Updateable(coolect).UpdateColumns((Collector u) => new { u.Status }).ExecuteCommand();
				await (from u in rep.Context.Updateable<ElectricMeter>().SetColumns((ElectricMeter u) => u.SignalStatus == 0)
					where u.SignalStatus == 1 && collectorIds.Contains(u.CollectorId.Value)
					select u).ExecuteCommandAsync();
				await rep.Context.Ado.CommitTranAsync();
			}
		}
		catch (Exception)
		{
			await rep.Context.Ado.RollbackTranAsync();
			throw;
		}
	}
}
